package com.umfwechat.lightprogram.controller.merchant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.DateTimesUtil;
import com.umfwechat.util.HttpUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.xml.XmlData;

/**
 * POS相关交易订单查询	每日交易列表-POS机、POS机交易详情
 * @author ChenFuLong
 *
 */
@Controller
@RequestMapping("/mystore")
public class PosOrderController {
	
	private static Logger logger = LoggerFactory.getLogger(PosOrderController.class);

	/**
	 * 每日交易列表-POS机
	 * 
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 * 	 */
	@RequestMapping(value="/getPosDayPayOrderList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject getPosDayPayOrderList(HttpServletRequest request, HttpServletResponse response){
		logger.info("【每日交易列表-POS机】开始"); 
		JSONObject result=new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			result.put("retCode", "0001");
			result.put("retMsg", "请求参数不足");
			logger.error("【每日交易列表-POS机】", e);
			return result;
		}
		//店铺编号
		String storeId = (String) json.get(CommonConsts.STOREID);

		//交易日期
		String orderDate = (String) json.get(CommonConsts.DATE);

		//交易类型
		String tranType = (String) json.get(CommonConsts.TRAN_TYPE);
		//银行卡类型
		String cardType = (String) json.get(CommonConsts.CARD_TYPE);
		
		String payType = (String) json.get(CommonConsts.PAY_TYPE); //筛选条件
		if (StringUtils.isBlank(payType)) {
			tranType = "";
			cardType = "";
		}else if ("3301".equals(payType) || "3501".equals(payType)) {	//交易类型(3301微信、3501支付宝)
			tranType = payType;
		}else if("00".equals(payType) || "02".equals(payType)){	//卡种(00：借记卡 02:准贷记卡)
			cardType = payType;
		}
		
		//当前页
		String currentPage = (String) json.get(CommonConsts.PAGE_NO);
		//每页条数
		String pageSize = (String) json.get(CommonConsts.PAGE_SIZE);
		
		try{
			if(StringUtil.isEmpty(storeId)){
				logger.info("店铺编号不能为空！"); 
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "店铺编号不能为空！");
				return result;
			}
			
			if(StringUtil.isEmpty(orderDate)){
				logger.info("交易日期不能为空！"); 
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "交易日期不能为空！");
				return result;
			}
			
			//商户交易查询接口 /offline-serv1/0901
			String url = UmfPropModel.INSTANCE.getPropValue("saas.pos.offlineserv10901");
			Map<String,Object> paramMap = new HashMap<String,Object>();
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			paramMap.put(CommonConsts.RPID, reqMessage.getRpid());
			paramMap.put(CommonConsts.REQDATE, reqMessage.getReqDate());
			paramMap.put(CommonConsts.REQTIME, reqMessage.getReqTime());
			//参数数据来源
			paramMap.put(CommonConsts.DATASOURCE, CommonConsts.SAAS);
			//当前页
			paramMap.put(CommonConsts.PAGE_NUM, currentPage);
			//每页显示记录数
			paramMap.put(CommonConsts.PAGE_SIZE, pageSize);
			//商户号
			paramMap.put(CommonConsts.MERCHANTID, storeId);
			//交易日期
			paramMap.put(CommonConsts.LOCALSYSDATE, orderDate.replaceAll("-", ""));
			//交易类型(3301微信、3501支付宝)
			paramMap.put(CommonConsts.TRAN_TYPE, tranType);
			//卡种(00：借记卡 02:准贷记卡)
			paramMap.put(CommonConsts.CARD_TYPE, cardType);
			
			logger.info("【商户交易查询】  路径：" + url + " 入参：" + paramMap);
			Map<String, Object> posMap = HttpUtil.httpPostForm2Xml(url, paramMap);
			logger.info("【商户交易查询】 出参：" + posMap);
			if(posMap == null || !RetCode.SUCCESS.equals(posMap.get(CommonConsts.RETCODE))){
				logger.info("【商户交易查询失败】");
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "商户交易查询失败！");
				return result;
			}
			
			List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
			Object listStr = posMap.get("listStr");
			if(listStr != null && StringUtil.isNotEmpty(listStr.toString())){
				List<Map<String, String>> posMapList = new Gson().fromJson(listStr.toString(), 
						new TypeToken<List<Map<String, String>>>(){}.getType());
				for(Map<String, String> map : posMapList){
					//获取交易类型名称
					String tranTypeName = getTranTypeName(map.get(CommonConsts.TRAN_TYPE), map.get(CommonConsts.PAY_TYPE));
					//获取卡类型名称
					String cardTypeName = getCardTypeName(map.get(CommonConsts.CARD_TYPE));
					
					//交易时间	
					String orderTime = "";
					if(StringUtil.isNotEmpty(map.get(CommonConsts.LOCALSYSDATE))
							&& StringUtil.isNotEmpty(map.get(CommonConsts.LOCALSYSTIME))){
						orderTime = DateTimesUtil.date18(map.get(CommonConsts.LOCALSYSDATE), map.get(CommonConsts.LOCALSYSTIME));
					}
					
					Map<String, String> dataMap = new HashMap<String, String>();
					//交易流水	
					dataMap.put(XmlData.TRADENO, map.get(XmlData.HOSTLSNO));
					//卡号	
					dataMap.put(XmlData.CARDNO, map.get(XmlData.CARDNO));
					//卡类型	
					dataMap.put(CommonConsts.CARD_TYPE, cardTypeName);
					//交易时间	
					dataMap.put(CommonConsts.DATETIME, orderTime);
					//交易金额(分转元)
					dataMap.put(CommonConsts.AMOUNT, map.get(CommonConsts.TRAN_AMT));
					//交易类型	
					dataMap.put(CommonConsts.PAY_TYPE, tranTypeName);
					//店铺编号
					dataMap.put(CommonConsts.STOREID, storeId);
					resultList.add(dataMap);
				}
			}
			result.put(CommonConsts.RETCODE, RetCode.SUCCESS);
			result.put(CommonConsts.RETMSG, "商户交易查询成功！");
			result.put("resultList", resultList);
			logger.info("【每日交易列表-POS机】返回数据：" + result); 
			return result;
		} catch (Exception e) {
			logger.info("获取每日交易列表-POS机失败",e);
			result.put(CommonConsts.RETCODE, RetCode.FAIL);
			result.put(CommonConsts.RETMSG, "获取每日交易列表-POS机失败");
			return result;
		}
	}
	
	/**
	 * POS机交易详情
	 * 
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 * 	 */
	@RequestMapping(value="/getPosPayOrder", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public JSONObject getPosPayOrder(HttpServletRequest request, HttpServletResponse response){
		logger.info("【POS机交易详情】 开始");
		JSONObject result=new JSONObject();
		String reqJSON = (String) request.getAttribute("_requestData");
		JSONObject json = null;
		try {
			json = JSONObject.fromObject(reqJSON);
		} catch (Exception e) {
			result.put("retCode", "0001");
			result.put("retMsg", "请求参数不足");
			logger.error("【POS机交易详情】", e);
			return result;
		}
		//交易流水
		String hostLsNo = (String) json.get(XmlData.TRADENO);
		//店铺编号
		String storeId = (String) json.get(XmlData.STORE_ID);
		//交易日期
		String orderDate = (String) json.get(XmlData.ORDERDATE);
		try{
			if(StringUtil.isEmpty(hostLsNo)){
				logger.info("交易流水不能为空！"); 
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "交易流水不能为空！");
				return result;
			}
 
			if(StringUtil.isEmpty(storeId)){
				logger.info("店铺编号不能为空！"); 
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "店铺编号不能为空！");
				return result;
			}
			
			if(StringUtil.isEmpty(orderDate)){
				logger.info("交易日期不能为空！"); 
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "交易日期不能为空！");
				return result;
			}
			
			//商户详情查询接口 /offline-serv1/0902
			String url = UmfPropModel.INSTANCE.getPropValue("saas.pos.offlineserv10902");
			Map<String,Object> paramMap = new HashMap<String,Object>();
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			paramMap.put(CommonConsts.RPID, reqMessage.getRpid());
			paramMap.put(CommonConsts.REQDATE, reqMessage.getReqDate());
			paramMap.put(CommonConsts.REQTIME, reqMessage.getReqTime());
			//参数数据来源
			paramMap.put(CommonConsts.DATASOURCE, CommonConsts.SAAS);
			//本地交易流水
			paramMap.put(XmlData.HOSTLSNO, hostLsNo);
			//商户号
			paramMap.put(CommonConsts.MERCHANTID, storeId);
			//交易日期
			paramMap.put(CommonConsts.LOCALSYSDATE, orderDate.substring(0, 10).replaceAll("-", ""));
			
			logger.info("【商户详情查询】  路径：" + url + " 入参：" + paramMap);
			Map<String, Object> posMap = HttpUtil.httpPostForm2Xml(url, paramMap);
			logger.info("【商户详情查询】 出参：" + posMap);
			if(!RetCode.SUCCESS.equals(posMap.get(CommonConsts.RETCODE))){
				logger.info("【商户详情查询失败】");
				result.put(CommonConsts.RETCODE, RetCode.FAIL);
				result.put(CommonConsts.RETMSG, "商户详情查询失败！");
				return result;
			}
			
			//获取交易类型名称
			String tranTypeName = getTranTypeName(StringUtil.trim(posMap.get(CommonConsts.TRAN_TYPE))
					,StringUtil.trim(posMap.get(CommonConsts.PAY_TYPE)));
			//获取交易状态名称
			String tranStateName = getTranStateName(StringUtil.trim(posMap.get(CommonConsts.SAF_FLAG))
					,StringUtil.trim(posMap.get(CommonConsts.SAF_FLAG)));
			//获取卡类型名称
			String cardTypeName = getCardTypeName(StringUtil.trim(posMap.get(CommonConsts.CARD_TYPE)));
			//交易时间	
			String orderTime = "";
			String localSysDate = StringUtil.trim(posMap.get(CommonConsts.LOCALSYSDATE));
			String localSysTime = StringUtil.trim(posMap.get(CommonConsts.LOCALSYSTIME));
			if(StringUtil.isNotEmpty(localSysDate)
					&& StringUtil.isNotEmpty(localSysTime)){
				orderTime = DateTimesUtil.date18(localSysDate, localSysTime);
			}
			
			//退费申请日期
			String refundDate = StringUtil.trim(posMap.get(CommonConsts.REFUND_DATE));
			if(StringUtil.isNotEmpty(refundDate)){
				refundDate = DateTimesUtil.date10(refundDate);
			}
			
			//交易金额(分转元)
			result.put(CommonConsts.AMOUNT, posMap.get(CommonConsts.TRAN_AMT));
			//交易时间
			result.put(CommonConsts.ORDERDATE, orderTime);
			//流水
			result.put(XmlData.TRADENO, StringUtil.trim(posMap.get(XmlData.HOSTLSNO)));
			//终端号
			result.put(CommonConsts.TERMINAL_ID, StringUtil.trim(posMap.get(CommonConsts.TERMINAL_ID)));
			//外部商户号
			result.put(CommonConsts.WMERCHANT_ID, StringUtil.trim(posMap.get(CommonConsts.WMERCHANT_ID)));
			//商户订单号
			result.put(CommonConsts.ORDER_NO, StringUtil.trim(posMap.get(CommonConsts.ORDER_NO)));
			//卡号
			result.put(XmlData.CARDNO, StringUtil.trim(posMap.get(XmlData.CARDNO)));
			//卡种
			result.put(CommonConsts.CARD_TYPE, cardTypeName);
			//参考号
			result.put(CommonConsts.TRAN_RRN, StringUtil.trim(posMap.get(CommonConsts.TRAN_RRN)));
			//交易类型
			result.put(CommonConsts.TRAN_TYPE, tranTypeName);
			//退费申请日期	
			result.put(CommonConsts.REFUND_DATE, refundDate);
			//交易状态
			result.put(CommonConsts.TRAN_STATE, tranStateName);
			result.put(CommonConsts.RETCODE, RetCode.SUCCESS);
			result.put(CommonConsts.RETMSG, "商户详情查询成功！");
			logger.info("【POS机交易详情】返回数据：" + result); 
			return result;
		} catch (Exception e) {
			logger.info("获取POS机交易详情失败",e);
			result.put(CommonConsts.RETCODE, RetCode.FAIL);
			result.put(CommonConsts.RETMSG, "获取POS机交易详情失败");
			return result;
		}
	}
	
	/**
	 * 支付类型名称
	 * 
	 * @param tranType 交易类型
	 * @param payType POS增值业务类型
	 * @return
	 */
	private String getTranTypeName(String tranType, String payType){

		String tranTypeName = "";
		if("1".equals(tranType)){
			if("3301".equals(payType) || "3305".equals(payType)){
				tranTypeName = "微信支付";
			}else if("3501".equals(payType) || "3505".equals(payType)){
				tranTypeName = "支付宝支付";
			}else{
				tranTypeName = "银行卡消费";
			}
		}else if("4".equals(tranType) || "5".equals(tranType)){
			tranTypeName = "预授权确认";
		}else if("9".equals(tranType)){
			tranTypeName = "退货";
		}else if("12".equals(tranType)){
			tranTypeName = "撤销";
		}else if("15".equals(tranType)){
			tranTypeName = "预授权通知";
		}else if("122".equals(tranType)){
			tranTypeName = "预授权申请撤销";
		}else if("123".equals(tranType)){
			tranTypeName = "预授权完成撤销";
		}
		return tranTypeName;
	}
	
	/**
	 * 卡类型名称
	 * 
	 * @param cardType 卡类型
	 * @return
	 */
	private String getCardTypeName(String cardType){
		String cardTypeName = "";
		if("00".equals(cardType)){
			cardTypeName = "借记卡";
		}else if("01".equals(cardType)){
			cardTypeName = "贷记卡";
		}
		return cardTypeName;
	}
	
	/**
	 * 支付状态名称
	 * 
	 * @param safFlag 冲正标识
	 * @param tranFlag 交易标识
	 * @return
	 */
	private String getTranStateName(String safFlag, String tranFlag){
		String tranStateName = "";
		if("1".equals(safFlag)){
			tranStateName = "已冲正";
		}else if("0".equals(tranFlag)){
			tranStateName = "正常";
		}else if("1".equals(tranFlag)){
			tranStateName = "已撤消";
		}else if("2".equals(tranFlag)){
			tranStateName = "已确认";
		}else if("4".equals(tranFlag)){
			tranStateName = "已退货";
		}else if("5".equals(tranFlag)){
			tranStateName = "未明";
		}
		return tranStateName;
	}
}
